<template>
  <div>
    <div class="front">
      <div class="front-left">
        <el-form class="front-form" :model="searchForm" ref='inventoryRef' :rules="inventoryOrderRules"
          label-width="120px">
          <el-form-item label="货品条码" class="front-input">
            <el-input v-model="searchForm.jadeCode" />
          </el-form-item>
          <el-form-item label="所属仓库" class="front-input">
            <el-select v-model="searchForm.warehouseId" placeholder="搜索匹配" style="">
              <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" class="front-input">
            <el-select v-model="searchForm.supplierId" placeholder="搜索匹配" style="" prop="supplierId">
              <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="front-right">
        <div class="right-photo">
          <video ref="videoElement" class="rigth-video" autoplay v-if="isvideo"></video>
          <canvas ref="canvasElement" class="right-img"></canvas>
        </div>
        <div class="right-action">
          <el-upload action="http://8.134.106.197:9001/common/uploadImage" class="upload"
            :headers="{ Authorization: token }" :show-file-list="false" accept=".png,.jpg,.jpeg,.webp"
            style="display: inline-block;" :name="file" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-error="console.log(error)" :on-success="handleUpload">
            <el-button @click="uploadImg" style="color:#1890ff;">上传</el-button>
          </el-upload>
          <el-button @click="takePhoto" style="color:#1890ff;margin-left: 10px;">拍照</el-button>
          <el-button @click="triggerCamera" style="color:#1890ff;">{{ cameraActive ? '关闭摄像头' : '打开摄像头' }}</el-button>
        </div>
      </div>
    </div>


    <div class="tail">
      <div class="tail-action">
        <el-button type="primary">导出明细</el-button>
        <el-button type="primary">打印明细</el-button>
        <el-button type="primary" @click="listUpdate">批量修改</el-button>
        <el-button type="primary" @click="listmoveUpdate">批量移仓</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
            @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>

      </div>
      <el-table :data="tableData()" border style="width: 100%" max-height="350" @selection-change="handleListChange">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column :selectable="selectable" type="selection" width="40" />
        <el-table-column label="货品图片" width="90">
          <template #default="scope">
            <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" fit="contain"
              style="max-height: 50px;max-width: 30px;" :preview-teleported="true" :lazy="true"
              :preview-src-list="imgPreview" @click="previewSrcList(scope.row.imageUrl)"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="货品编码" width="230">
          <template #default="scope">
            <div @click="handleCopy(scope.$index, scope.row)"
              style="display: flex;align-items: center;cursor: pointer;">{{ scope.row.jadeCode }}
              <Edit style="width: 1em; height: 1em; margin: 0 4px" />
            </div>

          </template>
        </el-table-column>
        <el-table-column v-for="item in inventoryJadeDataColumn" :prop="item.prop" :min-width="item.minWidth"
          :width="item.width" :max-width="item.maxWidth" :label="item.label" />
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openDetails(scope.row)">查看明细</el-button>
            <el-button link type="primary" size="small" @click="openEditRemarkDialog(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="handleDeleteRole(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <!-- 批量修改 -->
    <el-dialog v-model="dialogupdate" title="批量修改信息" width="35%" :close-on-click-modal="true">

      <el-form :model="supplierForm" label-width="120px" :rules="supplierRules" ref="supplierRef">
        <el-form-item label="数量" prop="jadeQuantity">
          <el-input v-model="supplierForm.jadeQuantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="品类" prop="jadeTypeId">
          <el-cascader :options="options" v-model="supplierForm.jadeTypeId" placeholder="请选择品类" ref="jadeCascaderRef"
            :props="{ expandTrigger: 'hover', emitPath: false }" @change="handleChangejadeType" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="成本价" prop="jadeCost">
          <el-input v-model="supplierForm.jadeCost" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="标签价" prop="jadeTagPrice">
          <el-input v-model="supplierForm.jadeTagPrice" placeholder="请输入标签价" />
        </el-form-item>
        <el-form-item label="货品状态" prop="inventoryStatus">
          <el-select v-model="supplierForm.inventoryStatus" placeholder="请选择货品状态" style="" prop="inventoryStatus">
            <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="supplierForm.supplierId" placeholder="请选择供应商" style="" prop="supplierId">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="remarkbutton" type="primary" @click="confirmListUpdate">确 定</el-button>
        <el-button class="remarkbutton" @click="closeListUpDialog">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 批量入库 -->
    <el-dialog v-model="dialogmove" title="批量修改信息" width="35%" :close-on-click-modal="true">

      <el-form :model="supplierFormmove" label-width="120px" :rules="supplierRules" ref="supplierRef">
        <el-form-item label="所属仓库" class="front-input">
          <el-select v-model="supplierFormmove.warehouseId" placeholder="搜索匹配" style="">
            <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属仓位" class="front-input">
          <el-select v-model="supplierFormmove.storageId" placeholder="搜索匹配" style="">
            <el-option v-for="item in selectedChildren" :key="item.id" :label="item.storageName" :value="item.id" />
          </el-select>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="remarkbutton" type="primary" @click="confirmmoveUpdate">确 定</el-button>
        <el-button class="remarkbutton" @click="closemoveUpDialog">取 消</el-button>
      </span>
    </el-dialog>

    <div class="optionView">
      <el-dialog v-model="dialogVisibleDetails">
        <el-descriptions border size="large" direction="vertical" title="排班基本信息">
          <el-descriptions-item label="直播店铺">{{ rowDetails.streamPlatform }}</el-descriptions-item>
          <el-descriptions-item label="代购费"><el-tag size="small">50</el-tag></el-descriptions-item>
          <el-descriptions-item label="直播班次">{{ rowDetails.streamShift }}</el-descriptions-item>
          <el-descriptions-item label="播货开始时间">{{ rowDetails.startTime }}</el-descriptions-item>
          <el-descriptions-item label="播货结束时间">{{ rowDetails.endTime }}</el-descriptions-item>
          <el-descriptions-item label="扣点比例">{{ rowDetails.deductionPoints }}</el-descriptions-item>
          <el-descriptions-item label="添加时间">{{ rowDetails.createTime }}</el-descriptions-item>
          <el-descriptions-item label="添加人">{{ rowDetails.createBy }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ rowDetails.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="修改人">{{ rowDetails.updateBy }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions border size="large" direction="vertical" title="直播人员信息" style="margin-top: 50px;">
          <el-descriptions-item label="售前客服"><el-tag size="small">张三</el-tag></el-descriptions-item>
          <el-descriptions-item label="直播助理"><el-tag size="small">张三</el-tag></el-descriptions-item>
          <el-descriptions-item label="场控"><el-tag size="small">张三</el-tag></el-descriptions-item>
          <el-descriptions-item label="主播"><el-tag size="small">张三</el-tag></el-descriptions-item>
          <el-descriptions-item label="其他人员"><el-tag size="small">张三</el-tag></el-descriptions-item>

        </el-descriptions>
      </el-dialog>
      <el-dialog v-model="dialogVisibleResult" title="检测结果" :close-on-press-escape="false" :close-on-click-modal="false"
        style="width: 350px;">
        <el-table :data="imageUrlList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" />
          <el-table-column label="查找对象" prop="url" width="120">
            <template #default="scope">
              <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.imageUrl" alt="Photo" fit="contain"
                style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
                :preview-src-list="imgPreview" @click="previewSrcList(scope.row.imageUrl)"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="识别结果" prop="matchUrl">
            <template #default="scope">
              <!-- <el-tooltip content="查无此货">
            </el-tooltip> -->
              <el-image :src="'http://8.134.106.197:9001/profile' + scope.row.matchUrl" alt="Photo" fit="contain"
                style="max-height: 120px;max-width: 70px;" :preview-teleported="true" :lazy="true"
                :preview-src-list="imgPreview" @click="previewSrcList(scope.row.matchUrl)">
                <template v-slot:error>
                  <i class="image-miss">{{ match_controll }}</i>
                </template>
              </el-image>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 15px;" @click="ensureJade">确认</el-button>
        <div>请勾选对象然后选择确认</div>
      </el-dialog>
    </div>
    <!-- 测试查看明细-->
    <div class="dialog-list">

      <el-drawer v-model="drawer" :direction="direction" size="35%">
        <el-descriptions border size="large" direction="vertical" title="货品详情">
          <el-descriptions-item label="图片"><el-image :src="'http://8.134.106.197:9001/profile' + rowDetails.imageUrl"
              style="height: 120px;width: 90px;" :preview-src-list="imgPreview"
              @click="previewSrcList(rowDetails.imageUrl)"></el-image></el-descriptions-item>
          <el-descriptions-item label="货品编码">{{ rowDetails.jadeCode }}</el-descriptions-item>
          <el-descriptions-item label="入库单号">{{ rowDetails.orderCode }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{ rowDetails.jadeWeight }}</el-descriptions-item>
          <el-descriptions-item label="供应商" width="150">{{ rowDetails.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="货品状态">{{ rowDetails.inventoryStatus }}</el-descriptions-item>
          <el-descriptions-item label="仓位名字" width="150">{{ rowDetails.storageName }}</el-descriptions-item>
          <el-descriptions-item label="仓库名字">{{ rowDetails.warehouseName }}</el-descriptions-item>
          <el-descriptions-item label="入库时间">{{ rowDetails.createTime }}</el-descriptions-item>
          <el-descriptions-item label="添加人">{{ rowDetails.createBy }}</el-descriptions-item>
        </el-descriptions>
      </el-drawer>
      <!-- 编辑备注的输入框 -->
      <el-dialog v-model="dialogVisible2" title="编辑备注" width="30%" :close-on-click-modal="true">

        <el-input v-model="editRemark" placeholder="请输入备注"></el-input>

        <span slot="footer" class="dialog-footer">
          <el-button class="remarkbutton" type="primary" @click="confirmUpdate">确 定</el-button>
          <el-button class="remarkbutton" @click="closeDialog">取 消</el-button>
        </span>
      </el-dialog>
    </div>

  </div>

</template>

<script>
import { defineComponent, reactive, toRefs, ref, onBeforeMount, onMounted, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { getSupplierList } from "@/api/user/user"
import { getWarehouseList, getStorageCascader } from '@/api/setting/setting';
import { getToken } from '@/utils/auth'
import { getJadeList, getJadeStatusList, deleteJade } from '@/api/inventory/inventory'
import { Plus, List } from '@element-plus/icons-vue';
import axios from 'axios'
import { getJadeCrop, jadeMatch, getJadeFeature, getJadeInfo, getUserList, getOutboundOrderCode, altJadeStatus } from '@/api/outbound/outbound'
import { getJadeType } from '@/api/inbound/inbound'

import { updateCheckRemark } from '@/api/auth/auth';
export default defineComponent({
  name: "HomeView",
  components: {
    Plus, List
  },
  setup() {
    const inventoryRef = ref(null)
    const videoElement = ref(null);//拍照相关参数
    const canvasElement = ref(null);
    const cameraActive = ref(false)
    const videoStream = ref(null)
    const isvideo = ref(true)
    const dialogVisibleImg = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const dialogVisibleDetails = ref(false)
    const dialogVisibleResult = ref(false)
    const match_controll = ref('识别中')
    const token = ref('')
    const clientList = ref([])//客户列表
    const imageUrlList = ref([])//图片相关参数
    const dialogImageUrl = ref('')
    const imgPreview = ref([])
    const tempData = ref([])
    const searchForm = reactive({  //入库表单数据
      jadeCode: '',
      warehouseId: '',
      supplierId: '',
    })
    const inventoryJadeInfoData = ref([])//表格数据
    const supplierList = ref([])//供应商列表
    const warehouseList = ref([])//仓库列表
    const inventoryOrderRules = reactive({//表单验证
      clientId: [{ required: true, message: '出库客户不能为空', trigger: 'change' },],
    });
    const inventoryForm = reactive({
      orderCode: '',
      inventoryType: 3,
      deptId: '1',
    });




    const inventoryJadeDataColumn = ref([])//表头数据
    const selectedFilters = ref([])

    const tableFilter = ref([//表头
      // { label: '货品编码', prop: 'jadeCode', width: '200', isSelected: true },
      { label: '入库单单号', prop: 'orderCode', width: '200', isSelected: true },
      { label: '数量', prop: 'jadeQuantity', width: '60', isSelected: true },
      { label: '品类', prop: 'jadeTypeName', width: '60', isSelected: true },
      { label: '成本价', prop: 'jadeCost', width: '70', isSelected: true },
      { label: '标签价', prop: 'jadeTagPrice', Width: '70', isSelected: true },
      { label: '货品状态', prop: 'inventoryStatus', width: '70', isSelected: true },
      { label: '供应商', prop: 'supplierName', width: '70', isSelected: true },
      { label: '入库仓库', prop: 'warehouseName', width: '70', isSelected: true },
      { label: '入库仓位', prop: 'storageName', width: '70', isSelected: true },
      { label: '入库类型', prop: 'orderType', width: '90', isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '90', isSelected: true },
      { label: '入库时间', prop: 'createTime', minWidth: '100', isSelected: true },
      { label: '备注', prop: 'remark', minWidth: '80', maxWidth: '80', isSelected: true },
    ])
    const statusList = ref([])//货品状态列表
    const options = ref([])//品类列表
    onBeforeMount(() => {//获取数据
      token.value = getToken()
      getUserList().then((res) => {
        clientList.value = res.rows
      })
      getStorageCascader().then((res) => {
        console.log('warehouseList', warehouseList)
        warehouseList.value = res
      })
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getOutboundOrderCode().then((res) => {
        inventoryForm.orderCode = res
      })
      getJadeStatusList().then((res) => {
        const trimmedString = res.statusList.slice(1, -1);
        const pairs = trimmedString.split(', ');
        // 转换为对象数组
        statusList.value = pairs.map(pair => {
          const [id, name] = pair.split('=');
          return { id: parseInt(id), name };
        });
      })
      getJadeType().then((res) => {
        res.data.forEach((item) => {
          if (item.children) {
            let temp = []
            item.children.forEach((item_c) => {
              temp.push({ value: item_c.id, label: item_c.jadeTypeName })
            })
            options.value.push({ value: item.id, label: item.jadeTypeName, children: temp }); // 将新的元素对象添加到结果数组中
          }
          else {
            options.value.push({ value: item.id, label: item.jadeTypeName }); // 将新的元素对象添加到结果数组中
          }
        })
        console.log('2', options.value)
      })
    })

    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inventoryJadeDataColumn.value.push(item)
        }
      })
      // 初始哈调取分页接口
      onSearch()
    })
    const handleCheckAllChange = (val) => {//全选按钮
      inventoryJadeDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inventoryJadeDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//设置勾选列状态
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inventoryJadeDataColumn.value = temp
      selectedFilters.value = inventoryJadeDataColumn.value.map(item => item.label)
    }

    ///查看明细
    const drawer = ref(false);
    const rowDetails = ref({});

    const openDetails = (row) => {//查看明细
      drawer.value = true;
      rowDetails.value = row;
    };
    //删除
    const handleDeleteRole = (jadeCode) => { //删除仓位
      ElMessageBox.confirm(
        '是否要删除该用户?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteJade(jadeCode).then(() => {
            getJadeList(state.data.page, state.data.limit)
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }





    //表格用到的参数
    const state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: inventoryJadeInfoData.value.length,
      }
    });
    //前端限制分页（tableData为当前展示页表格）
    const tableData = () => {
      return inventoryJadeInfoData.value
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.data.page = e;
      onSearch()
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.data.limit = e;
      onSearch()
    };

    const takePhoto = () => { //调用摄像头后拍照
      const video = videoElement.value
      const canvas = canvasElement.value
      if (cameraActive.value) {
        if (video) try {
          // 将视频画面绘制到画布上
          canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
          // 将画布内容转换为图片 URL
          // 将canvas内容转换为Blob对象
          canvas.toBlob(blob => {
            // 使用Blob对象创建URL
            const formData = new FormData()
            formData.append("file", blob, "image.png")
            // 使用 Axios 发送 POST 请求
            axios.post("http://8.134.106.197:9001/common/uploadImage", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                "Authorization": token.value,
              },
            }).then((res) => {
              getJadeCrop({ image_path: res.data.url.slice(34) }).then((res_crop) => {//分割图片
                if (res_crop.code == 500) {//是否分割出图片
                  ElMessage.error(res_crop)
                } else {
                  for (var key in res_crop.result) {
                    imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
                  }
                  let imageIds = imageUrlList.value.map(item => item.imageId)
                  getJadeFeature({ data: imageUrlList.value }).then(res => {
                    jadeMatch({ imageIds: imageIds }).then((res_match) => {//匹配翡翠
                      if (res_match.match_result == '') {
                        ElMessage.error('无法识别该货品')
                        imageUrlList.value = []
                      } else {
                        console.log(res_match.match_result)
                        imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                          const imageId = item.imageId;
                          const bestMatch = res_match.match_result[imageId];
                          console.log('匹配的图片' + bestMatch)
                          return { ...item, best_match: bestMatch };
                        })
                        getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                          jadeInfos.data.forEach(jade => {
                            imageUrlList.value.forEach(img => {
                              if (jade.imageId == img.best_match) {
                                img.matchUrl = jade.imageUrl
                                img.details = jade
                              }
                            })
                          })
                          console.log(imageUrlList.value)
                        })
                      }
                    })
                  })
                  dialogVisibleResult.value = true  //打开确认列表
                }
              })
            })
              .catch((error) => {
                // 处理上传失败的错误
                console.error(error)
              })
          });
        }
          catch (error) {
            ElMessage.error('摄像头拍照失败')
          }
      }
      else {
        ElMessage.error('请先打开摄像头')
      }

    };
    const triggerCamera = async () => { //启动摄像头
      if (cameraActive.value) {
        videoStream.value.getTracks().forEach(track => track.stop())//关闭摄像头代码
        videoElement.value.srcObject = null
        cameraActive.value = false
      } else {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
              videoStream.value = stream
              videoElement.value.srcObject = stream
              cameraActive.value = true
            })
            .catch(error => {
              ElMessage.error('获取摄像头失败')
            });
        }
        else {
          ElMessage.error('获取摄像头失败，请检查是否已连接摄像头')
        }

      }
    };
    const handleSelectionChange = (selection) => {
      selection.forEach((item) => {
        tempData.value.push(item)
      })
    }
    const ensureJade = () => {
      try {
        inventoryJadeInfoData.value = tempData.value
        tempData.value = []
        imageUrlList.value = []
        dialogVisibleResult.value = false
      } catch {
        ElMessage.error('请检测完成后再勾选')
      }

    }
    const handleUpload = (res) => {
      getJadeCrop({ image_path: res.url.slice(34) }).then((res_crop) => {//切割得到分割后的图列
        if (res_crop.code == 500) {//是否分割出图片
          ElMessage.error(res_crop)
        } else {
          for (var key in res_crop.result) {
            imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key] })
          }
          let imageIds = imageUrlList.value.map(item => item.imageId)
          getJadeFeature({ data: imageUrlList.value }).then(res => {
            jadeMatch({ imageIds: imageIds }).then((res_match) => {//匹配翡翠
              if (res_match.match_result == '') {
                ElMessage.error('无法识别该货品')
                imageUrlList.value = []
              } else {
                console.log(res_match.match_result)
                imageUrlList.value = imageUrlList.value.map(item => {//放入匹配结果
                  const imageId = item.imageId;
                  const bestMatch = res_match.match_result[imageId];
                  console.log('匹配的图片' + bestMatch)
                  return { ...item, best_match: bestMatch };
                })
                getJadeInfo({ imageIds: imageUrlList.value.map(i => i.best_match) }).then((jadeInfos) => {//获取翡翠信息
                  jadeInfos.data.forEach(jade => {
                    imageUrlList.value.forEach(img => {
                      if (jade.imageId == img.best_match) {
                        img.matchUrl = jade.imageUrl
                        img.details = jade
                      }
                    })
                  })
                  console.log(imageUrlList.value)
                })
              }
            })
          })
          dialogVisibleResult.value = true  //打开确认列表
        }
      })


    }
    const previewSrcList = (imgUrl) => {//预览图片
      imgPreview.value = []
      imgPreview.value.push('http://8.134.106.197:9001/profile' + imgUrl)
    }

    const changeOutboundType = (value) => {
      inventoryForm.inventoryShow1 = inventoryForm.inventoryShow2 = inventoryForm.inventoryShow3 = false
      value == 1 ? inventoryForm.inventoryShow1 = true : value == 2 ? inventoryForm.inventoryShow2 = true : inventoryForm.inventoryShow3 = true
    }
    const getStatus = () => {//得到货品应要改变的状态
      if (inventoryForm.inventoryShow1) {
        return 1
      } else if (inventoryForm.inventoryShow2) {
        return 2
      } else {
        return 3
      }
    }
    const onSearch = () => {//确认条码并搜索
      getJadeList(state.data.page, state.data.limit, searchForm.jadeCode, searchForm.supplierId, searchForm.warehouseId).then((res) => {
        inventoryJadeInfoData.value = res.rows
        console.log(inventoryJadeInfoData.value)
        state.data.total = res.total
      })
    }
    const onReset = () => {
      searchForm.jadeCode = searchForm.supplierId = searchForm.warehouseId = ''
      onSearch()
    }


    //编辑备注
    const editRemark = ref('');
    const dialogVisible2 = ref(false);
    const checkOrderIdValue = ref(null);

    const openEditRemarkDialog = (row) => {
      rowDetails.value = row;
      dialogVisible2.value = true;
      editRemark.value = row.remark;
      checkOrderIdValue.value = row.id;
    };

    const closeDialog = () => {
      dialogVisible2.value = false;
    };

    const confirmUpdate = () => {
      if (!rowDetails.value || !checkOrderIdValue.value || editRemark.value.trim() === '') {
        ElMessage.error('缺少有效的数据来更新备注');
        return;
      }

      const params = {
        checkOrderId: Number(checkOrderIdValue.value),
        remark: editRemark.value.trim(),
      };
      console.log('准备发送给后端的参数：', params);
      updateCheckRemark(params).then(response => {
        // 成功处理
        ElMessage.success('编辑备注成功');
        dialogVisible2.value = false;
        // 更新前端页面的备注值
        rowDetails.value.remark = editRemark.value;
      }).catch((error) => {
        console.error('更新备注失败：', error.response);
        ElMessage.error('修改备注失败，请重试');
      });
    };
    //点击复制
    const handleCopy = (index, row) => {
      // 获取需要复制的元素以及元素内的文本内容
      const text = row.jadeCode;
      const input = document.createElement("input");
      input.value = text;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
      ElMessage({
        message: "复制成功",
        type: "success",
      });
    }
    const selectable = (row) => ![1, 2].includes(row.id)
    const multipleSelection = ref([])// 选中的数据
    // 列表 全选
    const handleListChange = (val) => {
      multipleSelection.value = val
      console.log('选中的数据', multipleSelection)
    }
    const dialogupdate = ref(false)
    const dialogmove = ref(false)
    // 修改的信息
    const supplierForm = reactive({
      jadeQuantity: '',
      jadeTypeId: '',
      jadeCost: '',
      jadeTagPrice: '',
      inventoryStatus: '',
      supplierId: '',
    });
    const supplierFormmove = ref({
      warehouseId: '',
      storageId: ''
    });
    // 批量修改
    const listUpdate = () => {
      if (multipleSelection.value.length == 0) {
        ElMessage({
          type: 'warning',
          message: '请先选择列表数据',
        })
      } else {
        dialogupdate.value = !dialogupdate.value
      }
    }
    const jadeCascaderRef = ref(null)
    // 处理货品类型
    const handleChangejadeType = function (CascaderValue) {
      const pathArr = jadeCascaderRef.value.getCheckedNodes()[0].pathNodes
      const jadeNameId = pathArr[0].data.value
      const jadeTypeId = (pathArr[1] && pathArr[1].data) ? pathArr[1].data.value : null
      const idStr = jadeTypeId ? `${jadeNameId}-${jadeTypeId}` : `${jadeNameId}`
      // supplierForm.jadeTypeName = idStr
      console.log('idStr', idStr)
    }
    // 确认
    const confirmListUpdate = async () => {
      console.log('批量修改', supplierForm, multipleSelection.value);
      const promises = multipleSelection.value.map(item => {
        console.log({ id: item.id, ...supplierForm });
        return altJadeStatus({ id: item.id, ...supplierForm });
      });

      try {
        await Promise.all(promises);
        ElMessage({
          type: 'success',
          message: '修改成功',
        });

        closeListUpDialog()

        onSearch();
      } catch (error) {
        console.error('修改失败', error);
        ElMessage({
          type: 'error',
          message: '修改失败',
        });
      }
    };
    // 取消
    const closeListUpDialog = () => {
      supplierForm.jadeQuantity = '';
      supplierForm.jadeTypeName = '';
      supplierForm.jadeCost = '';
      supplierForm.jadeTagPrice = '';
      supplierForm.inventoryStatus = '';
      supplierForm.supplierName = '';

      dialogupdate.value = !dialogupdate.value
    }
    //批量入库
    const listmoveUpdate = () => {
      if (multipleSelection.value.length == 0) {
        ElMessage({
          type: 'warning',
          message: '请先选择列表数据',
        })
      } else {
        dialogmove.value = !dialogmove.value
      }
    }
    // 确定
    const confirmmoveUpdate = async () => {
      console.log('批量入库', supplierFormmove.value)
      const promises = multipleSelection.value.map(item => {
        console.log({ id: item.id, ...supplierFormmove.value });
        return altJadeStatus({ id: item.id, ...supplierFormmove.value });
      });

      try {
        await Promise.all(promises);
        ElMessage({
          type: 'success',
          message: '修改成功',
        });

        closemoveUpDialog()

        onSearch();
      } catch (error) {
        console.error('修改失败', error);
        ElMessage({
          type: 'error',
          message: '修改失败',
        });
      }
    }
    //  修改
    const closemoveUpDialog = () => {
      supplierFormmove.value.warehouseId = ''
      supplierFormmove.value.storageId = ''
      dialogmove.value = !dialogmove.value
    }
    const selectedChildren = ref([]); // 用于存储选中仓库的storages

    watch(() => supplierFormmove.value.warehouseId, (newVal) => {
      const selectedWarehouse = warehouseList.value.find(
        (item) => item.warehouseId === newVal
      );
      if (selectedWarehouse) {
        selectedChildren.value = selectedWarehouse.storages;
      } else {
        selectedChildren.value = [];
      }
      supplierFormmove.value.storageId = '';
    });
    return {
      inventoryJadeInfoData, token, imgPreview, imageUrlList, tempData, clientList, searchForm,
      inventoryForm, tableFilter, inventoryJadeDataColumn, selectedFilters, checkAll, isIndeterminate,
      state, inventoryOrderRules, inventoryRef, match_controll, supplierList, warehouseList, supplierFormmove, selectedChildren,
      videoElement, canvasElement, isvideo, cameraActive, videoStream, dialogupdate, supplierForm, statusList,
      dialogmove, listmoveUpdate, confirmmoveUpdate, closemoveUpDialog,
      options, handleChangejadeType, jadeCascaderRef, confirmListUpdate, closeListUpDialog,
      dialogVisibleImg, dialogImageUrl, dialogVisibleDetails, dialogVisibleResult, selectable, handleListChange, listUpdate,
      tableData, handleCheckAllChange, handleCheckChange, onSearch, onReset, handleCopy,
      handleCurrentChange, changeOutboundType,
      handleSizeChange, handleSelectionChange, ensureJade,
      triggerCamera, handleUpload, previewSrcList, takePhoto,
      ...toRefs(state), drawer,
      rowDetails,
      openDetails, openEditRemarkDialog, confirmUpdate, closeDialog, editRemark, checkOrderIdValue, dialogVisible2, handleDeleteRole
    };
  },
});
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  display: flex;
  height: 30%;
}

.front-left {
  height: 100%;
  background-color: #fff;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-self: flex-start;
  gap: 30px;
  width: 58%;

  .front-select {
    width: 80%;
    margin-left: 50px;
  }

  .front-form {
    .front-input {
      width: 400px;
    }

    .el-form-item__label {
      font-size: x-small;
    }
  }


}

.front-left-second {
  position: absolute;
  top: 400px;
  left: 240px;
}

.front-right {
  height: 100%;
  margin-left: 15px;
  background-color: #fff;
  padding: 10px;
  width: 40%;

  .right-photo {
    width: 100%;
    height: 80%;
    border: solid 1px;
  }

  .rigth-video {
    flex: auto;
    width: 100%;
    height: 100%;
  }

  .right-img {
    flex: auto;
    width: 100%;
    height: 100%;
    position: absolute;
    top: -9999px;
    opacity: 0;
  }

  .right-action {
    width: 100%;
    height: 40px;
    margin: 10px;
  }


  .imageBox {
    min-height: 100px;
    border-color: #000;
    border: solid 1px;
    padding: 5px;
    display: flex;
    flex-wrap: wrap;


    /* 图片之间的间距 */
    .imgList {
      /* 可根据需要调整每个图片元素的宽度 */
      margin-right: 10px;
      /* 图片之间的间距 */
      margin-bottom: 10px;
      /* 每行图片的底部间距 */
    }
  }

}



.tail {
  background-color: #fff;
  margin-top: 40px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}

.el-collapse {
  border-top: 0px;
  border-bottom: 0px;
}

.el-collapse-item__header {
  border-bottom: 0px;
}

.el-collapse-item__content {
  border-bottom: 0px;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>